import { useMutation } from "@tanstack/react-query";
import { registerAPI } from "@/api";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { useErrorHandler } from "@/lib/error-handler";
import { useRefreshCaptcha } from "./use-captcha";
import { useNavigate } from "react-router-dom";
import type { ErrorResponse, Response } from "@/types/response";
import type { AxiosError } from "axios";

/**
 * Register hooks
 */
export const useRegister = () => {
  const { t } = useTranslation();
  const errorHandler = useErrorHandler();
  const { mutate: refreshCaptcha } = useRefreshCaptcha();

  // Register mutation
  const registerMutation = useMutation({
    mutationFn: registerAPI.register,
    onSuccess: (response: Response) => {
      if (response.code === 200) {
        // 注册成功，显示成功弹窗
        toast.success(t("Registration successful"), {
          description:
            response.message ||
            t(
              "Your account has been created successfully. Please verify with your account email.",
              {
                defaultValue:
                  "Your account has been created successfully. Please verify with your account email.",
              }
            ),
          duration: 5000,
        });
      } else {
        // 注册失败，显示错误弹窗并刷新验证码
        toast.error(t("Registration failed"), {
          description:
            response.message ||
            t("An error occurred during registration. Please try again."),
          duration: 5000,
        });
      }
      // 刷新验证码
      refreshCaptcha();
    },
    onError: (error: AxiosError<ErrorResponse, unknown>) => {
      // 使用错误处理器获取错误信息
      const errorResult = errorHandler.handleApiError(error);

      // 根据错误类型显示不同颜色的弹窗
      if (errorResult.type === "warning") {
        toast.warning(t("Registration failed"), {
          description: errorResult.message,
          duration: 5000,
        });
      } else {
        toast.error(t("Registration failed"), {
          description: errorResult.message,
          duration: 5000,
        });
      }
      console.error("Registration error:", error);
    },
  });

  return {
    register: registerMutation.mutate,
    registerAsync: registerMutation.mutateAsync,
    isRegistering: registerMutation.isPending,
    registerError: registerMutation.error,
  };
};

/**
 * RegisterVerification hooks
 */
export const useVerify = () => {
  const { t } = useTranslation();
  const errorHandler = useErrorHandler();
  const { mutate: refreshCaptcha } = useRefreshCaptcha();
  const navigate = useNavigate();

  // Register mutation
  const verifyMutation = useMutation({
    mutationFn: registerAPI.verify,
    onSuccess: (response: Response) => {
      if (response.code === 200) {
        // 注册成功，显示成功弹窗
        toast.success(
          t("Registration verify successful", {
            defaultValue: "Registration verify successful",
          }),
          {
            description:
              response.message ||
              t(
                "Your account has been verfied successfully. Please login with your credentials.",
                {
                  defaultValue:
                    "Your account has been verfied successfully. Please login with your credentials.",
                }
              ),
            duration: 5000,
          }
        );
        // 验证成功后跳转到登录页
        navigate("/cas/login");
      } else {
        // 注册失败，显示错误弹窗并刷新验证码
        toast.error(t("Registration verify failed"), {
          description:
            response.message ||
            t("An error occurred during registration verify. Please try again."),
          duration: 5000,
        });
      }
      // 刷新验证码
      refreshCaptcha();
    },
    onError: (error: AxiosError<ErrorResponse, unknown>) => {
      // 使用错误处理器获取错误信息
      const errorResult = errorHandler.handleApiError(error);

      // 根据错误类型显示不同颜色的弹窗
      if (errorResult.type === "warning") {
        toast.warning(t("Registration verify failed"), {
          description: errorResult.message,
          duration: 5000,
        });
      } else {
        toast.error(t("Registration verify failed"), {
          description: errorResult.message,
          duration: 5000,
        });
      }
      console.error("Registration verify error:", error);
    },
  });

  return {
    verify: verifyMutation.mutate,
    verifyAsync: verifyMutation.mutateAsync,
    isVerifing: verifyMutation.isPending,
    verifyError: verifyMutation.error,
  };
};
